package com.yifang.yibingproject.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.yifang.yibingproject.utils.LogConst;
import com.yifang.yibingproject.utils.StringUtilOwn;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Configuration
@MapperScan({"com.yifang.yibingproject.mapper"})
public class MyBatisPlusConfig {
    /**
     * 开启MyBatis-Plus分页插件拦截器
     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        return new PaginationInterceptor();
//    }

    private static final ThreadLocal<String> logTableName = new ThreadLocal<>();

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 1-动态表名拦截器 （放到分页拦截器前面，分页才有效）
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put(LogConst.TABLE_PREFIX, ((sql, tableName) -> {
                String name = logTableName.get();
                if (StringUtilOwn.notEmpty(name)) {
                    return LogConst.TABLE_PREFIX + name;
                } else {
                    // 默认访问本月的
                    LocalDate now = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM");
                    return LogConst.TABLE_PREFIX + now.format(formatter);
                }
            }));
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        mybatisPlusInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

        // 2-分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor); // 开启分页

        return mybatisPlusInterceptor;
    }

}
